<template>
  <view class="list-page">
    <!-- 搜索栏 -->
    <view class="list-search-bar">
      <view class="list-search-input">
        <uni-icons type="search" size="16" color="#999"></uni-icons>
        <input v-model="queryParams.title" class="list-input" placeholder="搜索系统模块、操作功能"
               @input="handleSearchInput" @confirm="handleSearch"/>
        <uni-icons v-if="queryParams.title" type="clear" size="16" color="#999" @click="handleClear"></uni-icons>
      </view>
      <view class="list-filter-btn" @click="toggleFilter">
        <uni-icons type="filter" size="14" color="#666"></uni-icons>
        <text>筛选</text>
      </view>
    </view>

    <!-- 筛选抽屉 -->
    <uni-popup ref="filterPopup" type="right" :mask-click="false">
      <view class="list-filter-drawer">
        <view class="list-filter-header">
          <text class="list-filter-title">高级筛选</text>
          <uni-icons type="close" size="20" @click="closeFilter"></uni-icons>
        </view>
        <view class="list-filter-content">
          <view class="list-filter-item">
            <text class="list-filter-label">操作人员</text>
            <uni-easyinput v-model="queryParams.operName" placeholder="请输入操作人员" :clearable="true"/>
          </view>
          <view class="list-filter-item">
            <text class="list-filter-label">操作地址</text>
            <uni-easyinput v-model="queryParams.operIp" placeholder="请输入操作地址" :clearable="true"/>
          </view>
          <view class="list-filter-item">
            <text class="list-filter-label">操作类型</text>
            <BottomSelect v-model="queryParams.businessType" :options="operTypeOptions" value-field="value"
                          label-field="text" placeholder="请选择操作类型" title="选择操作类型"/>
          </view>
          <view class="list-filter-item">
            <text class="list-filter-label">操作状态</text>
            <BottomSelect v-model="queryParams.status" :options="statusOptions" value-field="value" label-field="text"
                          placeholder="请选择状态" title="选择状态"/>
          </view>
        </view>
        <view class="list-filter-footer">
          <view class="btn btn-reset" @click="handleFilterReset">重置</view>
          <view class="btn btn-confirm" @click="handleFilterConfirm">确定</view>
        </view>
      </view>
    </uni-popup>

    <!-- 操作按钮栏 -->
    <view class="list-action-bar">
      <view class="btn btn-danger" @click="handleClean">
        <uni-icons type="trash" size="14" color="#ff3b30"/>
        <text>清空</text>
      </view>
      <view class="btn btn-default" @click="handleRefresh">
        <uni-icons type="reload" size="14" color="#666"/>
        <text>刷新</text>
      </view>
    </view>

    <!-- 列表 -->
    <view class="list-content">
      <view v-for="log in operlogList" :key="log.operId" class="list-item" @click="handleView(log)">
        <view class="list-avatar">
          <uni-icons :type="getOperTypeIcon(log.businessType)" size="24"
                     :color="getOperTypeIconColor(log.businessType)"></uni-icons>
        </view>
        <view class="list-info">
          <view class="list-header">
            <text class="list-title">{{ log.title }}</text>
            <text class="list-subtitle">{{ log.operName }}</text>
            <view class="status-badge"
                  :class="(log.status === '0' || log.status === 0) ? 'status-normal' : 'status-disabled'">
              {{ (log.status === '0' || log.status === 0) ? '成功' : '失败' }}
            </view>
          </view>
          <view class="list-details">
            <view class="detail-item">
              <uni-icons type="list" size="14" color="#999"/>
              <text class="detail-text">ID：{{ log.operId }}</text>
            </view>
            <view class="detail-item">
              <uni-icons type="flag" size="14" color="#999"/>
              <DictTag :options="sys_oper_type" :value="log.businessType" size="mini"/>
            </view>
            <view class="detail-item">
              <uni-icons type="location" size="14" color="#999"/>
              <text class="detail-text">{{ log.operIp }}</text>
            </view>
            <view class="detail-item">
              <uni-icons type="calendar" size="14" color="#999"/>
              <text class="detail-text">{{ parseTime(log.operTime, '{y}-{m}-{d} {h}:{i}') }}</text>
            </view>
            <view class="detail-item" v-if="log.costTime">
              <uni-icons type="clock" size="14" :color="log.costTime > 1000 ? '#ff9500' : '#52c41a'"/>
              <text class="detail-text">{{ log.costTime }}ms</text>
            </view>
          </view>
        </view>
        <view class="list-actions">
          <view class="action-btn action-primary" @click.stop="handleView(log)">
            <uni-icons type="eye" size="14" color="#007aff"/>
            <text class="action-text">详情</text>
          </view>
          <view class="action-btn action-danger" @click.stop="handleDelete(log)">
            <uni-icons type="trash" size="14" color="#ff3b30"/>
            <text class="action-text">删除</text>
          </view>
        </view>
      </view>
    </view>

    <view v-if="operlogList.length > 0" class="list-load-more">
      <uni-load-more :status="loadStatus" :content-text="loadText" @clickLoadMore="handleLoadMore"/>
    </view>

    <view v-if="!loading && operlogList.length === 0" class="list-empty">
      <uni-icons type="info" size="48" color="#ddd"/>
      <text class="list-empty-text">暂无操作日志</text>
    </view>
  </view>
</template>

<script setup>
import {computed, getCurrentInstance, onMounted, reactive, ref} from 'vue'
import {cleanOperlog, delOperlog, list} from '@/api/monitor/operlog'
import {parseTime} from '@/utils/ruoyi'
import {BottomSelect} from '@/components/select'
import {useDict} from '@/utils/dict'
import DictTag from '@/components/DictTag'

const {proxy} = getCurrentInstance()

// 字典数据
const {sys_oper_type} = useDict('sys_oper_type')

// 数据定义
const operlogList = ref([])
const total = ref(0)
const loading = ref(false)
const loadStatus = ref('more')
const filterPopup = ref(null)
let searchTimer = null

const loadText = reactive({
  contentdown: '上拉显示更多',
  contentrefresh: '正在加载...',
  contentnomore: '没有更多数据了'
})

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  title: '',
  operName: '',
  operIp: '',
  businessType: '',
  status: ''
})

// 操作类型选项（转换格式）
const operTypeOptions = computed(() => {
  const options = [{value: '', text: '全部类型'}]
  if (sys_oper_type.value && sys_oper_type.value.length > 0) {
    options.push(...sys_oper_type.value.map(item => ({
      value: item.value,
      text: item.label
    })))
  }
  return options
})

// 状态选项
const statusOptions = [
  {value: '', text: '全部状态'},
  {value: '0', text: '成功'},
  {value: '1', text: '失败'}
]


// 页面加载
onMounted(() => {
  getList()
})

// 获取操作日志列表
async function getList() {
  if (loading.value) return

  loading.value = true
  loadStatus.value = 'loading'

  try {
    const response = await list(queryParams)
    if (response.code === 200) {
      const newData = response.rows || []

      if (queryParams.pageNum === 1) {
        operlogList.value = newData
      } else {
        operlogList.value.push(...newData)
      }

      total.value = response.total || 0

      if (operlogList.value.length >= total.value) {
        loadStatus.value = 'noMore'
      } else {
        loadStatus.value = 'more'
      }
    }
  } catch (error) {
    console.error('获取操作日志列表失败:', error)
    proxy.$modal.showToast('获取操作日志列表失败')
    loadStatus.value = 'more'
  } finally {
    loading.value = false
  }
}

// 筛选相关函数
function toggleFilter() {
  filterPopup.value.open()
}

function closeFilter() {
  filterPopup.value.close()
}

function handleFilterConfirm() {
  closeFilter();
  handleQuery()
}

function handleFilterReset() {
  Object.assign(queryParams, {
    pageNum: 1,
    pageSize: 10,
    title: '',
    operName: '',
    operIp: '',
    businessType: '',
    status: ''
  })
}

function handleSearchInput() {
  if (searchTimer) clearTimeout(searchTimer)
  searchTimer = setTimeout(() => {
    handleQuery()
  }, 300)
}

function handleSearch() {
  handleQuery()
}

function handleClear() {
  queryParams.title = '';
  handleQuery()
}

// 获取操作类型图标
function getOperTypeIcon(businessType) {
  const iconMap = {
    '0': 'more',
    '1': 'plus',
    '2': 'compose',
    '3': 'trash',
    '4': 'gear',
    '5': 'download',
    '6': 'upload',
    '7': 'logout',
    '8': 'code',
    '9': 'clear'
  }
  return iconMap[businessType] || 'more'
}

// 获取操作类型图标颜色（保留用于图标显示）
function getOperTypeIconColor(businessType) {
  const colorMap = {
    '0': '#8c8c8c',
    '1': '#52c41a',
    '2': '#1890ff',
    '3': '#ff4d4f',
    '4': '#faad14',
    '5': '#13c2c2',
    '6': '#722ed1',
    '7': '#fa541c',
    '8': '#eb2f96',
    '9': '#f5222d'
  }
  return colorMap[businessType] || '#8c8c8c'
}

// 获取操作类型样式类
function getOperTypeClass(businessType) {
  const classMap = {
    '0': 'tag-default',
    '1': 'tag-success',
    '2': 'tag-primary',
    '3': 'tag-error',
    '4': 'tag-warning',
    '5': 'tag-info',
    '6': 'tag-info',
    '7': 'tag-warning',
    '8': 'tag-info',
    '9': 'tag-error'
  }
  return classMap[businessType] || 'tag-default'
}

// 注：getDictLabel 函数已从 utils/dict.js 导入

function handleLoadMore() {
  if (loadStatus.value === 'more') {
    queryParams.pageNum++
    getList()
  }
}

// 查询
function handleQuery() {
  queryParams.pageNum = 1
  operlogList.value = []
  getList()
}

// 业务操作方法
function handleView(log) {
  uni.navigateTo({
    url: `./detail?operId=${log.operId}`
  })
}

async function handleDelete(log) {
  try {
    await proxy.$modal.confirm(`确认要删除编号为"${log.operId}"的操作日志吗？`)

    const response = await delOperlog(log.operId)
    if (response.code === 200) {
      proxy.$modal.showToast('删除成功')
      handleQuery()
    }
  } catch (error) {
    console.error('删除操作日志失败:', error)
  }
}


async function handleClean() {
  try {
    await proxy.$modal.confirm('确认要清空所有操作日志吗？')

    const response = await cleanOperlog()
    if (response.code === 200) {
      proxy.$modal.showToast('清空成功')
      handleQuery()
    }
  } catch (error) {
    console.error('清空操作日志失败:', error)
  }
}


function handleRefresh() {
  handleQuery()
}
</script>

<style lang="scss" scoped>
@import '@/styles/list-page.scss';
</style>